export { pluginDistPackageJsonFile }

// We create a file `dist/server/package.json` to support ESM users.
// Otherwise, following error is thrown:
//   Must use import to load ES Module: dist/server/pageFiles.js
//   require() of ES modules is not supported.
//   require() of dist/server/pageFiles.js from node_modules/vike/dist/esm/node/runtime/page-files/setup.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
// Reproduction: https://github.com/brillout/vite-plugin-ssr-server-import-syntax

import type { Plugin, ResolvedConfig } from 'vite'
import { rollupIsEsm } from '../shared/rollupIsEsm.js'
import { isViteServerSide } from '../shared/isViteServerSide.js'

function pluginDistPackageJsonFile(): Plugin[] {
  let config: ResolvedConfig
  return [
    {
      name: 'telefunc:pluginDistPackageJsonFile',
      apply: 'build',
      configResolved: {
        handler(config_) {
          config = config_
        },
      },
      generateBundle: {
        handler(options, bundle) {
          if (!isViteServerSide(config, this.environment)) return
          const isEsm = rollupIsEsm(options)
          const fileName = 'package.json'
          if (bundle[fileName]) return // E.g. already generated by Telefunc / Vike
          this.emitFile({
            fileName,
            type: 'asset',
            source: getPackageJsonContent(isEsm),
          })
        },
      },
    },
  ]
}

function getPackageJsonContent(isEsm: boolean): string {
  if (isEsm) {
    return `{ "type": "module" }`
  } else {
    return `{ "type": "commonjs" }`
  }
}
